import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {UndoRedoService} from '../../services/undo-redo.service';
import {SaveStateService} from '../../services/save-state.service';
import {TablesService} from '../../services/tables.service';
import {NotesService} from '../../services/notes.service';
import {AreasService} from '../../services/areas.service';

interface Tool {
  id: string;
  name: string;
  icon?: string;
}

@Component({
  selector: 'app-toolbar',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent {
  undoRedoService = inject(UndoRedoService);
  saveStateService = inject(SaveStateService);
  tablesService = inject(TablesService);
  notesService = inject(NotesService);
  areasService = inject(AreasService);

  selectedTool = 'table';

  tools: Tool[] = [
    {id: 'table', name: '表格'},
    {id: 'note', name: '注释'},
    {id: 'area', name: '区域'}
  ];

  undo() {
    this.undoRedoService.undo();
  }

  redo() {
    this.undoRedoService.redo();
  }

  selectTool(toolId: string) {
    this.selectedTool = toolId;
  }

  addTable() {
    const newTable = {
      id: `table_${Date.now()}`,
      name: '新表格',
      x: Math.random() * 300 + 100,
      y: Math.random() * 200 + 100,
      fields: [
        {
          id: `field_${Date.now()}`,
          name: 'id',
          type: 'INTEGER',
          primaryKey: true,
          notNull: true,
          increment: true
        }
      ]
    };
    this.tablesService.addTable(newTable);
    this.saveStateService.markUnsaved();
  }

  addNote() {
    const newNote = {
      id: `note_${Date.now()}`,
      content: '新注释',
      x: Math.random() * 300 + 100,
      y: Math.random() * 200 + 100,
      width: 200,
      height: 100,
      color: '#fef3c7'
    };
    this.notesService.addNote(newNote);
    this.saveStateService.markUnsaved();
  }

  addArea() {
    const newArea = {
      id: `area_${Date.now()}`,
      name: '新区域',
      x: Math.random() * 300 + 100,
      y: Math.random() * 200 + 100,
      width: 300,
      height: 200,
      color: '#dbeafe'
    };
    this.areasService.addArea(newArea);
    this.saveStateService.markUnsaved();
  }

  getToolButtonClass(toolId: string): string {
    const baseClass = 'px-3 py-2 rounded text-sm font-medium transition-colors';
    const activeClass = 'bg-blue-100 text-blue-700 border border-blue-200';
    const inactiveClass = 'bg-gray-50 text-gray-700 border border-gray-200 hover:bg-gray-100';

    return `${baseClass} ${this.selectedTool === toolId ? activeClass : inactiveClass}`;
  }

  formatLastSaved(date: Date): string {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  }
}
